import React from 'react';
import { Alert } from 'antd';
import { connect } from 'umi';

import TMainBasePage from '@/base/TMainBasePage';
import { TRDefault } from '@/components/index.js';
import emitter from '#/utils/events';
import renovate from '#/utils/renovate';

import Header from './components/Header';
import Main from './components/Main';
import styles from './index.less';

@connect(({ global }) => ({
  buttonPermissions: global.configure.buttonPermissions,
  menuCode: global.configure.menuCode,
}))
export default class ManyShorttermForecast extends TMainBasePage {
  constructor(props) {
    super(props);
    this._settlement_ = {};
    this._isPositionLoading_ = true;
    this.state.signature = '';
    this.state.selectValue = '';
    this.state.selectChildren = '';
    this.state.dateValue = [];
    this.state.isShow = false;
    this.state.isFresh = false;
  }
  async componentWillMount() {
    await this._onGetStation(() => {
      const { stationList = [] } = this.state;
      this.onChangeUnitFn(stationList?.[0]?.value);
      this.setState(
        {
          stationList: stationList.map((m) => {
            this._settlement_[m.value] = m.children || [];
            return { lable: m.lable, value: m.value };
          }),
        },
        () => {
          this._isPositionLoading_ = false;
          this.setState({ flag: true });
        },
      );
    }, this.props.menuCode);
  }

  async componentDidMount() {
    this.__beforeunload = this.beforeunload.bind(this);
    window.addEventListener('beforeunload', this.__beforeunload);
    emitter.on('onChangeUnit', this.onChangeUnitFn.bind(this));
  }
  componentWillUnmount() {
    super.componentWillUnmount();
    this.__beforeunload && window.removeEventListener('beforeunload', this.__beforeunload);
  }
  beforeunload(e) {
    if (renovate.isRenovate) {
      let confirmationMessage = '当前工作将不被保存，继续执行此操作？';
      (e || window.event).returnValue = confirmationMessage;
      return confirmationMessage;
    }
  }
  _onGetStationName(array, arr = []) {
    let keyVal = array?.find((item) => item.value == arr[0] || '')?.lable;
    var end = arr[arr.length - 1];
    array.forEach((item) => {
      if (item.children) {
        item.children.forEach((jitem) => {
          if (end === jitem.stationId) {
            keyVal += '/' + jitem.stationName;
          }
        });
      }
    });
    return keyVal;
  }
  onChangeUnitFn(value) {
    this.setState({
      selectValue: value,
      selectChildren: undefined,
      dateValue: [],
      isShow: false,
    });
  }

  // onRegionChange(stations, value) {
  //   // 切换省份
  //   const newstationTree = [];
  //   const _stations = stations.filter((x) => value.includes(x._companyName));
  //   const _groups = _.groupBy(_stations, '_regionName');
  //   Object.values(_groups).map((item) => {
  //     item.map((y) => {
  //       newstationTree.push({
  //         value: y._stationCode,
  //         label: y._stationName,
  //         selectId: y._stationCode,
  //       });
  //     });
  //   });
  //   return newstationTree;
  // }

  renderEmpty() {
    return (
      <div style={{ width: '100%', height: '80%', marginTop: '15%' }}>
        <TRDefault type="emptysm" />
        <div className={styles.message}>
          <Alert
            message={<span className={styles.spnColor}>请添加查询条件</span>}
            type="warning"
            showIcon
          />
        </div>
      </div>
    );
  }
  onSearch(val) {
    this.setState({
      dateValue: val,
      isFresh: !this.state.isFresh,
    });
  }
  render() {
    const { newStationList, newSelectStationList, stationList, dateValue, isFresh } = this.state;
    const { buttonPermissions = [] } = this.props;
    const newstations = [];
    newStationList.map((x) => {
      // 公司
      (x?.children || []).map((y) => {
        // 省份
        (y?.children || []).map((z) => {
          // 场站
          newstations.push(z);
        });
      });
    });
    const newstationTree = newStationList?.find(
      (i) => i.marketId === newSelectStationList[0],
    )?.children;

    const stationIds = _.flatten(newstationTree?.map((i) => i?.children));

    if (this._isPositionLoading_) {
      return this._onLoadingRender(false);
    }
    if (stationList.length === 0) {
      return this._onEmptyRender();
    }
    return (
      <div className={styles.page}>
        <div className={styles.tool}>
          <div>{this?._onStationSelectRender()}</div>
          <Header settlementUnitLists={newstationTree} onSearch={this.onSearch.bind(this)} />
        </div>
        <Main
          dateValue={dateValue}
          stationId={Number(stationIds?.[0]?.stationId) || ''}
          stationIds={stationIds}
          isFresh={isFresh}
          buttonPermissions={buttonPermissions}
        />
      </div>
    );
  }
}

ManyShorttermForecast.propTypes = {};
